package com.example.saifly.mainPage.plan;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Application.MyApplication;
import com.example.common.Fragment;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.Model.DailyPlanBg;
import com.example.saifly.Model.DailyPlans;
import com.example.saifly.R;
import com.example.saifly.ReceiverAndService.AlarmReceiver;
import com.example.saifly.inPageMy.Artical;
import com.example.saifly.inPagePlan.TodoActivity;
import com.example.saifly.inPagePlan.article.ArticleDetailActivity;
import com.example.saifly.inPagePlan.chat.ChatActivity;
import com.example.saifly.inPagePlan.cureMethod.CureMethodActivity;
import com.example.saifly.inPagePlan.dailyQuestion.DailyQuestionActivity;
import com.example.saifly.inPageRecord.WriteBodyActivity;
import com.example.saifly.inPageRecord.WriteEnvironmentActivity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
import static com.example.common.Util.TimeUtil.Date2StringHM;


public class PlanFragment extends Fragment {

    private LinearLayout cure_method, todo, assistant, recommend_title;
    private TextView now_time, now_title;
    String nextPlanContext = "暂无",nextPlanTime = "暂无";
    private boolean isTodayPlanFinish = false;
    private EditText etLoginCode;
    private boolean showTag = false;
    private EditText etName, etTime;//
    private LinearLayout set_physical_data,set_environmental_data,set_questionnaire;        //用于设置身体数据，环境数据，问卷调查点击
    private SharedPreferences sp=MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
    private String nowDateString;                                                           //记录今日的时间，用于判断是否录入了手动录入数据
    private int physicalFinish = 0,environmentFinish = 0,dailyQesFinish = 0;

    private String patientPhone;
    private String recommendArticleContent;   //推荐文章的内容
    private String recommendArticleID;    //推荐文章ID
    private String uid;
    private Intent intent;     //界面传值

    private TextView tvRevommendArticle;
    private Boolean patientOrFamily;

    //接受每日计划，按时间排序展示最新的计划提醒
    List<DailyPlanBg> dailyPlanBgList;
    List<DailyPlans> dailyPlansList;

    //每次从其他activity中返回时，实时更新数据
    @Override
    public void onResume() {
        super.onResume();
        InitSetDailyData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                GetDailyPlans(sp.getString("uid","15678565964"),new Date().getTime());
                SetAlarm();          //定时提醒执行计划和健康评估
            }
        }).start();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_plan;
    }

    @Override
    protected void init(){

        new Thread(new Runnable() {
            @Override
            public void run()
            {
                RecommendArticleList();
            }
        }).start();

        //初始化数据
        InitData();
        if(sp.getString("identity", "patient").equals("patient")){
            patientOrFamily = true;
        }
        else {
            patientOrFamily = false;
        }

        cure_method = getActivity().findViewById(R.id.plan_cure_method);
        todo = getActivity().findViewById(R.id.plan_todo);
        assistant = getActivity().findViewById(R.id.plan_assistant);
        recommend_title = getActivity().findViewById(R.id.plan_recommend_title);
        now_time = getActivity().findViewById(R.id.plan_now_time);
        now_title = getActivity().findViewById(R.id.plan_now_title);
        tvRevommendArticle=getActivity().findViewById(R.id.plan_recommend_article);
        uid=sp.getString("uid","110");
        intent= new Intent(getActivity(), ArticleDetailActivity.class); //从当前界面跳转到文章详情

        //设置跳转事件
        initJump();
    }

    private void InitData() {
        dailyPlanBgList = new ArrayList<>();
        dailyPlansList = new ArrayList<>();
    }

    //目前存在延时，大约5-10秒
    private void SetAlarm(){
        //如果没有录入医嘱则不设置闹钟

        if(getActivity() == null) return ;
        AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);//获取AlarmManager实例
        //AlarmManager.ELAPSED_REALTIME：3，表示闹钟在手机睡眠状态下不可用，该状态下闹钟使用相对时间
        //AlarmManager.ELAPSED_REALTIME_WAKEUP：2，表示闹钟在睡眠状态下会唤醒系统并执行提示功能，该状态下闹钟使用相对时间
        //AlarmManager.RTC：1，表示闹钟在睡眠状态下不可用，该状态下闹钟使用绝对时间，即当前系统时间
        //AlarmManager.RTC_WAKEUP，0：表示闹钟在睡眠状态下会唤醒系统并执行提示功能，该状态下闹钟使用绝对时间
        //System.currentTimeMillis()：当前系统的绝对时间。SystemClock.elapsedRealtime()：当前系统的相对时间，即开机到现在的毫秒数
        long systemTime = System.currentTimeMillis()+1000;
        Intent intent = new Intent(getActivity(), AlarmReceiver.class);

        PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, intent, FLAG_UPDATE_CURRENT);
        manager.set(AlarmManager.RTC_WAKEUP, systemTime, pi);//开启提醒
    }


    private void InitSetDailyData(){
        //将当前日期转化为年-月-日，发送给后端，得到今日的计划
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        nowDateString = dateFormat.format(date);

        Log.d("123", "InitSetDailyData: "+date);
        Long longdate = date.getTime();
        new Thread(new Runnable() {
            @Override
            public void run() {
                GetPhysical(uid,longdate);
                GetEnvironment(uid,longdate);
                GetDailyQes(uid,longdate);
                //        判断是否已经录入每日手动录入数据
                if(getActivity() == null) return ;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(patientOrFamily == true && physicalFinish == 0)
                        {
                            set_physical_data.setVisibility(set_physical_data.VISIBLE);
                            set_physical_data.setOnClickListener(v->startActivity(new Intent(getActivity(), WriteBodyActivity.class)));
                        }
                        else
                        {
                            set_physical_data.setVisibility(set_physical_data.GONE);
                        }
                        if(patientOrFamily == true && environmentFinish == 0)
                        {
                            set_environmental_data.setVisibility(set_environmental_data.VISIBLE);
                            set_environmental_data.setOnClickListener(v->startActivity(new Intent(getActivity(), WriteEnvironmentActivity.class)));
                        }
                        else
                        {
                            set_environmental_data.setVisibility(set_environmental_data.GONE);
                        }
                        if(patientOrFamily == true && dailyQesFinish == 0)
                        {
                            set_questionnaire.setVisibility(set_questionnaire.VISIBLE);
                            set_questionnaire.setOnClickListener(v->startActivity(new Intent(getActivity(), DailyQuestionActivity.class)));
                        }
                        else
                        {
                            set_questionnaire.setVisibility(set_questionnaire.GONE);
                        }
                    }
                });
            }
        }).start();


        Log.d("date",sp.getString("dateWriteEnvironmentalData","default"));

        set_physical_data = getActivity().findViewById(R.id.plan_set_physical_data);
        set_environmental_data = getActivity().findViewById(R.id.plan_set_environmental_data);
        set_questionnaire = getActivity().findViewById(R.id.plan_set_questionnaire);

    }

    //获取文章推荐
    private interface getRecommendArticle {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/getRecommendArticle")
        Call<ResponseBody> RecommendArticleList(@Body JSONObject jsonObject);
    }

    private void RecommendArticleList() {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        getRecommendArticle apiRecommendArticleList = retrofit.create(getRecommendArticle.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("patientPhone", 123);
//        Log.d("啦啦啦啦", "logData: "+jsonObject);

        Call<ResponseBody> call = apiRecommendArticleList.RecommendArticleList(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    Artical recommendArticle=JSON.parseObject(result.getJSONObject("result").toString(),Artical.class);
                    String articleTitle=recommendArticle.getTitle();   //获取文章标题
                    tvRevommendArticle.setText("今日推荐:"+articleTitle);

                    recommendArticleContent=recommendArticle.getLink();  //获取文章内容
                    recommendArticleID=recommendArticle.getArticalId();   //获取文章ID

                    intent.putExtra("RecommendArticleContent", recommendArticleContent);
                    intent.putExtra("RecommendArticleID",recommendArticleID);
                    intent.putExtra("key", 4);
                    //Log.d("文章链接", "logData: "+recommendArticleContent);
                }
                else{
                    if(getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
//                            showMyToast(toast,10*500);// 设置显示时间  一次10ms,显示500次，即显示5s
                            }
                        });
                    }
                }
            }
        } catch (Exception e) {
            if(getActivity() != null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            e.printStackTrace();
        }
    }

    //Toast 自定义显示时长
    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer =new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        },0,3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt );
    }
//
//    private class addListeners implements View.OnClickListener       //调用系统浏览器
//    {
//        @Override
//        public void onClick (View v) {
//            if(v.getId()==R.id.plan_recommend_title)
//            {
//                Uri uri = Uri.parse(recommendArticleLink);
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                intent.setData(uri);
//                startActivity(intent);
//            }
//        }
//    }

    private void initJump() {
        cure_method.setOnClickListener(v -> startActivity(new Intent(getActivity(), CureMethodActivity.class)));
        todo.setOnClickListener(v -> startActivity(new Intent(getActivity(), TodoActivity.class)));
        recommend_title.setOnClickListener(v ->startActivity(intent));
        assistant.setOnClickListener(v -> startActivity(new Intent(getActivity(), ChatActivity.class)));
        //还缺客服的部分
    }

    //获取身体数据、环境数据、每日问卷是否填写完成
    private interface ApiGetFinish{
        @Headers({"Content-Type:application/json"})                                         //大家都不变
        @POST("/estimate/judgeBodyData")                                                    //后端给的路径
        Call<ResponseBody> GetPhysical(@Body JSONObject jsonObject);
        @POST("/estimate/judgeEnvironmentData")                                             //后端给的路径
        Call<ResponseBody> GetEnvironment(@Body JSONObject jsonObject);
        @POST("/estimate/judgeDailyQuestionnaire")                                          //后端给的路径
        Call<ResponseBody> GetDailyQes(@Body JSONObject jsonObject);
    }

    private void GetPhysical(String patientPhone,Long longdate){
        JSONObject jsonObject = new JSONObject();

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetFinish apiGetFinish = retrofit.create(ApiGetFinish.class);
        jsonObject.put("patientPhone",patientPhone);
        jsonObject.put("date",longdate);

        Call<ResponseBody> call = apiGetFinish.GetPhysical(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    physicalFinish = (int) result.get("result");
                }
                else{
                    if(getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        } catch (IOException e) {
            if(getActivity() != null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            e.printStackTrace();
        }
    }

    private void GetEnvironment(String patientPhone,Long longdate){
        JSONObject jsonObject = new JSONObject();

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetFinish apiGetFinish = retrofit.create(ApiGetFinish.class);
        jsonObject.put("patientPhone",patientPhone);
        jsonObject.put("date",longdate);

        Call<ResponseBody> call = apiGetFinish.GetEnvironment(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    environmentFinish = (int) result.get("result");
                }
                else{
                    if(getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        } catch (IOException e) {
            if(getActivity() != null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            e.printStackTrace();
        }
    }

    private void GetDailyQes(String patientPhone,Long longdate){
        Log.d("123", "GetDailyQes: "+longdate);
        JSONObject jsonObject = new JSONObject();

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetFinish apiGetFinish = retrofit.create(ApiGetFinish.class);
        jsonObject.put("patientPhone",patientPhone);
        jsonObject.put("date",longdate);

        Call<ResponseBody> call = apiGetFinish.GetDailyQes(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    dailyQesFinish = (int) result.get("result");
                }
                else{
                    if(getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        } catch (IOException e) {
            if(getActivity() != null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                    }
                });
                e.printStackTrace();
            }
        }
    }

    //获取每日计划，并显示离当前时间最近的计划事项
    private interface ApiGetDailyPlans{
        @Headers({"Content-Type:application/json"})                             //大家都不变
        @POST("/arrange/getDailyPlan")                                          //后端给的路径
        Call<ResponseBody> GetDailyPlan(@Body JSONObject jsonObject);
    }

    private void GetDailyPlans(String patientPhone,Long date){
        JSONObject jsonObject = new JSONObject();

        RetrofitHelper retrofitHelper=new RetrofitHelper();     //大家都一样
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetDailyPlans apiGetDailyPlan = retrofit.create(ApiGetDailyPlans.class);
        jsonObject.put("patientPhone",patientPhone);
        jsonObject.put("date",date);

        Call<ResponseBody> call = apiGetDailyPlan.GetDailyPlan(jsonObject);
        final Response<ResponseBody> response;
        try{
            response = call.execute();
            Log.d("123", "GetDailyPlans: "+response);
            if(response.body() != null){
                JSONObject resultJson=JSON.parseObject(response.body().string());
                if(resultJson.getInteger("code")!=null&&resultJson.getInteger("code")==1){
                    String result = resultJson.get("result").toString();
                    String resultDP = JSON.parseObject(result).get("dailyPlans").toString();
                    dailyPlanBgList = JSON.parseArray(resultDP,DailyPlanBg.class);
                    if(dailyPlanBgList.isEmpty()){
                        if(getActivity() != null && sp.getString("identity","patient").equals("patient")){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "您还未输入医嘱，请及时输入！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                    else {
                        dailyPlansList.clear();
                        for(int i = 0; i < dailyPlanBgList.size(); i++){
                            dailyPlansList.add(new DailyPlans(dailyPlanBgList.get(i).getContent(),Date2StringHM(dailyPlanBgList.get(i).getTime()),dailyPlanBgList.get(i).getPlanId()));
                        }
                        Collections.sort(dailyPlansList);

                        String nowtime = Date2StringHM(new Date());
                        String tomorrowFirstPlanTime = dailyPlansList.get(0).getContent_time();     //记录明天的第一项计划时间和内容，方便app提醒用户
                        String tomorrowFirstPlanContext = dailyPlansList.get(0).getContent_title();
                        for(int i = 0; i < dailyPlansList.size(); i++){
                            nextPlanTime = dailyPlansList.get(i).getContent_time();
//                            Log.d("123", "nextPlanTime: "+nextPlanTime);
//                            Log.d("123", "nowtime: "+nowtime);
                            if(nowtime.compareTo(nextPlanTime) < 0){
                                nextPlanContext = dailyPlansList.get(i).getContent_title();
                                break;
                            }
                        }
                        if(nowtime.compareTo(nextPlanTime) < 0){
                            //今日还有未完成任务
                            isTodayPlanFinish = false;
                            sp.edit()
                                    .putString("nextPlanContext",nextPlanContext)
                                    .putString("nextPlanTime",nextPlanTime)
                                    .putString("nextPlanTimeHour",nextPlanTime.split(":")[0])
                                    .putString("nextPlanTimeMinute",nextPlanTime.split(":")[1])
                                    .apply();
                        }
                        else{
                            //今日任务已完成
                            isTodayPlanFinish = true;
                            sp.edit()
                                    .putString("nextPlanContext",tomorrowFirstPlanContext)
                                    .putString("nextPlanTime","明日计划："+tomorrowFirstPlanTime)
                                    .putString("tomorrowFirstPlanTimeHour",tomorrowFirstPlanTime.split(":")[0])
                                    .putString("tomorrowFirstPlanTimeMinute",tomorrowFirstPlanTime.split(":")[1])
                                    .apply();
                        }
                        if(getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    now_time.setText(sp.getString("nextPlanContext","暂无"));
                                    now_title.setText(sp.getString("nextPlanTime","无执行时间"));
                                }
                            });
                        }
                    }
                }
                else {
                    if(getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        } catch (IOException e) {
            if(getActivity() != null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            e.printStackTrace();
        }
    }
}